package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.common.vo.UserLoginRespVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author LaiSanShan
 * @date 2021-08-19
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @return 结果响应
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        // 1.后台限制60秒后才可发送
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotBlank(redisCode)) {
            long timeOld = Long.parseLong(redisCode.split("_")[1]);
            long timeNow = System.currentTimeMillis();
            // 60秒内不能再发
            if (timeNow - timeOld < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 获取code
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartyFeignService.sendCode(phone, code);

        // 2.验证码的校验，redis缓存验证码
        redisTemplate.opsForValue()
                .set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        return R.ok();
    }

    /**
     * 注册成功，跳转登录页面
     * 校验不通过，转发注册页面
     *
     * @param redirectAttributes 模拟重定向携带数据
     * @return view
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes redirectAttributes) {
        // 1.校验不通过，转发到注册页
        if (result.hasErrors()) {
            // 错误收集
            Map<String, String> errorMap = result.getFieldErrors().stream()
                    // 对key去重收集成集合
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(()
                            -> new TreeSet<>(Comparator.comparing(FieldError::getField))), ArrayList::new))
                    .stream()
                    // 封装成map
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", errorMap);
            redirectAttributes.addFlashAttribute("errors", errorMap);

            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验验证码
        String code = vos.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (StringUtils.isNotBlank(redisCode)) {
            redisCode = redisCode.split("_")[0];
        }
        if (!StringUtils.equalsIgnoreCase(code, redisCode)) {
            HashMap<String, String> errorMap = new HashMap<>();
            errorMap.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errorMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 删除验证码
        redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());

        // 调用远程进行注册
        R r = memberFeignService.regist(vos);
        if (r.getCode() == 0) {
            // 注册成功
            return "redirect:http://auth.gulimall.com/login.html";
        } else {
            // 注册失败
            HashMap<String, String> errorMap = new HashMap<>();
            errorMap.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errorMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    /**
     * 登录页面
     *
     * @return 跳转页面
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            return "login";
        } else {
            // 登录过，跳往首页
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {

        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            // 登录成功
            UserLoginRespVo loginRespVo = r.getData("data", new TypeReference<UserLoginRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, loginRespVo);
            return "redirect:http://gulimall.com";
        } else {
            // 登录失败
            HashMap<String, String> errorMap = new HashMap<>();
            errorMap.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errorMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

}
